<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Exception\BaseException;
use App\Service\Member\AuthService;
use App\Utils\Log;
use Hyperf\Utils\Context;
use Hyperf\Utils\Coroutine;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AppAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $request->getQueryParams()['token'] ?? '';

        if (empty($token)) {
            $token = $request->getParsedBody()['token'] ?? '';
        }

        if (empty($token)) {
            $token = $request->getHeader('token')[0] ?? '';
        }
        // 如果验证失败 则提示前端重新登陆
        $memberData = AuthService::getInstance()->getInfo(AuthService::TYPE_APP, $token);
        if (!$memberData || empty($memberData['id'])) {
            throw new BaseException(BaseException::TOKEN_ERROR);
        }
        set_user_info($memberData);
        return $handler->handle($request);
    }
}
